package com.example.userservice.service.impl;

import com.example.common.constant.OperationType;
import com.example.common.constant.RoleConstant;
import com.example.common.dto.*;
import com.example.common.exception.NotFoundException;
import com.example.common.feign.PermissionFeignClient;
import com.example.common.util.CryptoUtils;
import com.example.common.util.JwtUtils;
import com.example.userservice.entity.UserEntity;
import com.example.userservice.mq.RocketMQProducer;
import com.example.userservice.repository.UserRepository;
import com.example.userservice.service.UserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PermissionFeignClient permissionFeignClient;
    private final RocketMQProducer rocketMQProducer;
    private final JwtUtils jwtUtils;

    @Autowired
    public UserServiceImpl(UserRepository userRepository,
                           PermissionFeignClient permissionFeignClient,
                           RocketMQProducer rocketMQProducer,
                           JwtUtils jwtUtils) {
        this.userRepository = userRepository;
        this.permissionFeignClient = permissionFeignClient;
        this.rocketMQProducer = rocketMQProducer; // 修复1：确保注入RocketMQProducer
        this.jwtUtils = jwtUtils; // 修复2：确保注入JwtUtils
    }

    @Override
    @GlobalTransactional // Seata分布式事务
    @Transactional
    public ApiResponse<String> register(UserDTO userDTO, String clientIp) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(userDTO.getUsername())) {
            return ApiResponse.error(400, "用户名已存在");
        }

        // 创建用户实体
        UserEntity user = new UserEntity();
        BeanUtils.copyProperties(userDTO, user);
        user.setPassword(CryptoUtils.encodePassword(userDTO.getPassword()));

        // 保存用户（分库分表）
        UserEntity savedUser = userRepository.save(user);

        try {
            // 调用权限服务绑定默认角色
            ApiResponse<Void> bindResponse = permissionFeignClient.bindDefaultRole(savedUser.getUserId());
            if (bindResponse.getCode() != 0) {
                throw new RuntimeException("绑定角色失败: " + bindResponse.getMessage());
            }

            // 发送注册日志
            Map<String, Object> detail = new HashMap<>();
            detail.put("username", userDTO.getUsername());
            detail.put("email", userDTO.getEmail());

            OperationLogEvent logEvent = new OperationLogEvent();
            logEvent.setUserId(savedUser.getUserId());
            logEvent.setAction(OperationType.REGISTER);
            logEvent.setIp(clientIp);
            logEvent.setDetail(detail);

            rocketMQProducer.sendLogMessage(logEvent); // 修复3：使用正确的rocketMQProducer实例

            // 生成JWT Token
            String token = jwtUtils.generateToken(savedUser.getUserId(), RoleConstant.USER); // 修复4：使用RoleConstant
            return ApiResponse.success(token);
        } catch (Exception e) {
            throw new RuntimeException("注册失败", e);
        }
    }

    @Override
    public ApiResponse<String> login(String username, String password) {
        // 修复5：使用Optional正确处理可能为空的情况
        Optional<UserEntity> userOpt = userRepository.findByUsername(username);
        UserEntity user = userOpt.orElseThrow(() -> new NotFoundException("用户不存在"));

        if (!CryptoUtils.matchesPassword(password, user.getPassword())) {
            return ApiResponse.error(401, "密码错误");
        }

        // 获取用户角色
        ApiResponse<String> roleResponse = permissionFeignClient.getUserRoleCode(user.getUserId());
        if (roleResponse.getCode() != 0) {
            return ApiResponse.error(500, "获取角色信息失败: " + roleResponse.getMessage());
        }

        String token = jwtUtils.generateToken(user.getUserId(), roleResponse.getData());
        return ApiResponse.success(token);
    }

    @Override
    public ApiResponse<UserDTO> getUserInfo(Long userId) {
        // 修复6：使用Optional正确处理可能为空的情况
        Optional<UserEntity> userOpt = userRepository.findById(userId);
        UserEntity user = userOpt.orElseThrow(() -> new NotFoundException("用户不存在"));

        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(user, dto);
        return ApiResponse.success(dto);
    }

    @Override
    @Transactional
    public ApiResponse<Void> updateUser(Long userId, UserDTO userDTO) {
        // 修复7：使用Optional正确处理可能为空的情况
        Optional<UserEntity> userOpt = userRepository.findById(userId);
        UserEntity user = userOpt.orElseThrow(() -> new NotFoundException("用户不存在"));

        // 更新允许修改的字段
        if (userDTO.getEmail() != null) user.setEmail(userDTO.getEmail());
        if (userDTO.getPhone() != null) user.setPhone(userDTO.getPhone());

        userRepository.save(user);
        return ApiResponse.success(null);
    }

    @Override
    @Transactional
    public ApiResponse<Void> resetPassword(Long userId, String newPassword) {
        // 修复8：使用Optional正确处理可能为空的情况
        Optional<UserEntity> userOpt = userRepository.findById(userId);
        UserEntity user = userOpt.orElseThrow(() -> new NotFoundException("用户不存在"));

        user.setPassword(CryptoUtils.encodePassword(newPassword));
        userRepository.save(user);
        return ApiResponse.success(null);
    }
}